package khleuven.mondzorg.db.readers;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import khleuven.mondzorg.db.DBException;
import khleuven.mondzorg.domain.DentalCareApp;
import khleuven.mondzorg.domain.DomainException;
import khleuven.mondzorg.domain.Entry;
import khleuven.mondzorg.domain.EntryType;
import khleuven.mondzorg.domain.Illustration;
import khleuven.mondzorg.domain.MondAppEntry;

/**
 * Creates Entries for the app based on hardcoded, online or offline information.
 * 
 * @author u0055909
 */
public abstract class EntryBuilder {
	
	protected EntryBuilder() throws DBException{
		reloadAllIllustrationsFromSource();
		reloadAllEntriesFromSource();
	}
	
	protected abstract void reloadAllIllustrationsFromSource() throws DBException;
	protected abstract void reloadAllEntriesFromSource() throws DBException;

	
	public void createEntriesFromJSonArray(JSONArray mondappentries,
									       EntryType entry_type, 
			                               Constructor<? extends MondAppEntry> entryConstructor) 
			                 throws DBException {
		for(int i=0; i < mondappentries.length(); i++) {
			try {
				JSONObject object = mondappentries.getJSONObject(i);
				add(entryConstructor.newInstance(object));
			} catch (JSONException e) {
				throw new RuntimeException(e); // should not occur - TODO ignore error for this entry?
			} catch (IllegalArgumentException e) {
				throw new RuntimeException(e); // should not occur
			} catch (InstantiationException e) {
				throw new RuntimeException(e); // should not occur
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e); // should not occur
			} catch (InvocationTargetException e) {
				throw new RuntimeException(e); // should not occur
			}
		}
	}
	
	// In GoogleSpreadsheet worden illustraties via deze methode toegevoegd..
	public void add(MondAppEntry mondappentry) throws DBException{
		try{
			if(mondappentry instanceof Illustration){
				Illustration ill = (Illustration)(mondappentry);
				DentalCareApp.getInstance().add(ill);
			} else{
				Entry entry = (Entry)(mondappentry);
				DentalCareApp.getInstance().add(entry);
			}
		} catch(DomainException e){
			throw new DBException("Cannot add entry to app",e);
		}
	}
}
